package utils

import (
	"encoding/json"
	"io"
	"net"
	"net/http"
	"strings"
	"time"
)

var client *http.Client

func init() {
	client = &http.Client{
		Timeout: 5 * time.Second,
		Transport: &http.Transport{
			IdleConnTimeout:     2 * time.Minute,
			TLSHandshakeTimeout: 5 * time.Second,
			DialContext: (&net.Dialer{
				Timeout:   5 * time.Second,
				KeepAlive: 10 * time.Minute,
				DualStack: true,
			}).DialContext,
		},
	}
}

func HttpGet(url string) ([]byte, error) {

	rsp, err := client.Get(url)
	if err != nil {
		return nil, err
	}
	defer rsp.Body.Close()

	return io.ReadAll(rsp.Body)
}

func HttpPostJson(url string, body interface{}) ([]byte, error) {

	bodyStr, err := json.Marshal(body)
	if err != nil {
		return nil, err
	}
	return httpPost(url, "application/json", string(bodyStr))
}

func HttpPostXml(url string, xmlBody string) ([]byte, error) {

	return httpPost(url, "application/xml", xmlBody)
}

func httpPost(url string, contentType string, body string) ([]byte, error) {

	rsp, err := client.Post(url, contentType, strings.NewReader(body))
	if err != nil {
		return nil, err
	}
	defer rsp.Body.Close()

	return io.ReadAll(rsp.Body)
}
